package com.iplay.component.im.jpush;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.iplay.component.im.IMComponent;
import com.iplay.component.im.IMException;
import com.iplay.component.im.Message;
import com.iplay.component.im.OutgoingMessage;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jmessage.api.JMessageClient;
import cn.jmessage.api.common.model.RegisterInfo;
import cn.jmessage.api.common.model.message.MessageBody;
import cn.jmessage.api.message.SendMessageResult;

@Component("JPush")
public class JPush implements IMComponent {

	private static final Logger LOGGER = LoggerFactory.getLogger(JPush.class);

	@Value("${jpush.app-key}")
	private String appKey;
	@Value("${jpush.master-secret}")
	private String masterSecret;
	@Value("${jpush.admin}")
	private String admin;

	@Override
	public boolean createUser(String username, String password) throws IMException {
		JMessageClient client = getJMessageClient();
		try {
			List<RegisterInfo> users = new ArrayList<RegisterInfo>();
			RegisterInfo user = RegisterInfo.newBuilder().setUsername(username).setPassword(password).build();
			users.add(user);
			RegisterInfo[] regUsers = new RegisterInfo[users.size()];
			String res = client.registerUsers(users.toArray(regUsers));
			LOGGER.debug(res);
		} catch (APIConnectionException e) {
			LOGGER.error("JPush server connection error. Please retry later. ", e);
			throw new IMException(e.getMessage(), e);
		} catch (APIRequestException e) {
			LOGGER.error("Error response from JPush server. Please review and fix it. ", e);
			throw new IMException(e.getMessage(), e);
		}
		return true;
	}

	@Override
	public void sendMessage(String receiver, String message) throws IMException {
		JMessageClient client = getJMessageClient();
		try {
			MessageBody body = MessageBody.text(message);
			SendMessageResult result = client.sendSingleTextByAdmin(receiver, admin, body);
			LOGGER.debug(result.toString());
		} catch (APIConnectionException e) {
			LOGGER.error("JPush server connection error. Please retry later. ", e);
			throw new IMException(e.getMessage(), e);
		} catch (APIRequestException e) {
			LOGGER.error("Error response from JPush server. Please review and fix it. ", e);
			throw new IMException(e.getMessage(), e);
		}
	}

	private JMessageClient getJMessageClient() {
		return new JMessageClient(appKey, masterSecret);
	}

	@Override
	public void sendMessage(String receiver, Message message) throws IMException {
		JMessageClient client = getJMessageClient();
		try {
			MessageBody body = MessageBody.newBuilder().addExtras(message.getExtra()).setText(message.getBody())
					.build();
			SendMessageResult result = client.sendSingleTextByAdmin(receiver, admin, body);
			LOGGER.debug(result.toString());
		} catch (APIConnectionException e) {
			LOGGER.error("JPush server connection error. Please retry later. ", e);
			throw new IMException(e.getMessage(), e);
		} catch (APIRequestException e) {
			LOGGER.error("Error response from JPush server. Please review and fix it. ", e);
			throw new IMException(e.getMessage(), e);
		}
	}

	@Override
	public boolean deleteUser(String username) throws IMException {
		JMessageClient client = getJMessageClient();
		try {
			client.deleteUser(username);
		} catch (APIConnectionException e) {
			LOGGER.error("JPush server connection error. Please retry later. ", e);
			throw new IMException(e.getMessage(), e);
		} catch (APIRequestException e) {
			LOGGER.error("Error response from JPush server. Please review and fix it. ", e);
			throw new IMException(e.getMessage(), e);
		}
		return true;
	}

	@Override
	public void sendMessage(OutgoingMessage message) throws IMException {
		sendMessage(message.getReceiver(), message.getMessage());
	}

	@Override
	public void modifyUserPassword(String username, String password) throws IMException {
		JMessageClient client = getJMessageClient();
		try {
			client.updateUserPassword(username, password);
		} catch (APIConnectionException e) {
			LOGGER.error("JPush server connection error. Please retry later. ", e);
			throw new IMException(e.getMessage(), e);
		} catch (APIRequestException e) {
			LOGGER.error("Error response from JPush server. Please review and fix it. ", e);
			throw new IMException(e.getMessage(), e);
		}
	}
}
